﻿using IceCS.AsposeProd.Core;
using IceCS.AsposeProd.Core.Services;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.IO;

namespace IceCS.AsposeProd.WebApi.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class DocConvertController : ControllerBase
    {
        private readonly ILogger<DocConvertController> _logger;
        private readonly DocConvertService _docConvertService;

        public DocConvertController(DocConvertService docConvertService, ILogger<DocConvertController> logger, IHostEnvironment env)
        {
            _logger = logger;
            _docConvertService = docConvertService;
            _docConvertService.GenPagesFolderPath = Path.Combine(env.ContentRootPath,"wwwroot", _docConvertService.HtmlPageBaseFolderName);
        }

        [HttpPost("ConvertWordToHtml")]
        public ActionResult ConvertWordToHtml(IFormFile file)
        {
            if (file == null)
            {
                return BadRequest(new
                {
                    Msg = "please select a word(.doc/.docx) file",
                });
            }
            var fileName = file.FileName;
            var extName = Path.GetExtension(fileName).ToLower();
            if (!(extName == ".doc" || extName == ".docx"))
            {
                return BadRequest(new
                {
                    Msg = "only support .doc/.doc file",
                });
            }

            try
            {
                var fs = file.OpenReadStream();
                _logger.LogInformation($"开始转换 word 文档：{fileName}");
                _docConvertService.ConvertWordToHtml1(fileName, fs);
                var path = $"{Request.Scheme}://{Request.Host}/{_docConvertService.HtmlPageBaseFolderName}/{fileName}/{_docConvertService.HtmlPageName}";
                _logger.LogInformation($"转换 word 文档：{fileName} 成功，路径：{path}");
                return Ok(new
                {
                    Msg = "convert word doc success",
                    PageUrl = path
                });
            }
            catch (Exception ex)
            {
                return BadRequest(new
                {
                    Msg = "throw an error",
                    Exception = ex
                });
            }
        }

        [HttpPost("ConvertPdfToHtml")]
        public ActionResult ConvertPdfToHtml(IFormFile file)
        {
            if (file == null)
            {
                return BadRequest(new
                {
                    Msg = "please select a pdf(.pdf) file",
                });
            }
            var fileName = file.FileName;
            var extName = Path.GetExtension(fileName).ToLower();
            if (!(extName == ".pdf"))
            {
                return BadRequest(new
                {
                    Msg = "only support .pdf file",
                });
            }

            try
            {
                var fs = file.OpenReadStream();
                _logger.LogInformation($"开始转换 pdf 文档：{fileName}");
                _docConvertService.ConvertPdfToHtml1(fileName, fs);
                var path = $"{Request.Scheme}://{Request.Host}/{_docConvertService.HtmlPageBaseFolderName}/{fileName}/{_docConvertService.HtmlPageName}";
                _logger.LogInformation($"转换 pdf 文档：{fileName} 成功，路径：{path}");
                return Ok(new
                {
                    Msg = "convert pdf doc success",
                    PageUrl = path
                });
            }
            catch (Exception ex)
            {
                return BadRequest(new
                {
                    Msg = "throw an error",
                    Exception = ex
                });
            }
        }

        [HttpGet("ExportHtmlToWord/{fileName}")]
        public ActionResult ExportHtmlToWord(string fileName)
        {
            try
            {
                var fileContent = System.IO.File.ReadAllTextAsync(Path.Combine(_docConvertService.GenPagesFolderPath, fileName, "index.html")).Result;
                var phyPath = $"{_docConvertService.GenPagesFolderPath}\\{_docConvertService.HtmlPageAssetsFolderName}";
                var d = new DirectoryInfo(phyPath);
                phyPath = d.FullName;
                fileContent = fileContent.Replace($"src=\"{_docConvertService.HtmlPageAssetsFolderName}", $"src=\"{phyPath}");
                var fs = _docConvertService.ConvertHtmlToWord(fileContent);
                return File(fs, "application/octet-stream", fileName + ".docx");
            }
            catch (Exception ex)
            {
                return BadRequest(new
                {
                    Msg = "throw an error",
                    Exception = ex
                });
            }
        }

        [HttpGet("ExportHtmlToPdf/{fileName}")]
        public ActionResult ExportHtmlToPdf(string fileName)
        {
            try
            {
                var fileContent = System.IO.File.ReadAllTextAsync(Path.Combine(_docConvertService.GenPagesFolderPath, fileName, "index.html")).Result;
                var fs = _docConvertService.ConvertHtmlToPDF(fileContent);
                return File(fs, "application/octet-stream", fileName + ".pdf");
            }
            catch (Exception ex)
            {
                return BadRequest(new
                {
                    Msg = "throw an error",
                    Exception = ex
                });
            }
        }
    }
}
